<script lang="ts" setup>
import { ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { fetchSave } from '@/service/api/group';
import GroupStaff from './staff.vue';
const formRef = ref<FormInstance>();
defineOptions({ name: 'GroupEdit' });

interface Emits {
  (e: 'reload'): void;
}
const emit = defineEmits<Emits>();
const enable = ref(true);
const show = ref(false);
const model = ref<Api.GroupEntity.GroupModel>({
  id: 0,
  name: '',
  staffCount: 0,
  createdTime: '',
  updateTime: ''
});

function resetModel() {
  model.value.id = 0;
  model.value.name = '';
  model.value.staffCount = 0;
  model.value.createdTime = '';
  model.value.updateTime = '';
}
function init(item: any) {
  if (item) Object.assign(model.value, item);
  else resetModel();
  show.value = true;
}
function save() {
  formRef.value?.validate(async valid => {
    if (!valid) {
      window.$notification?.error('表单不完整，请检查');
      return;
    }
    enable.value = false;
    fetchSave(model.value).then(res => {
      enable.value = true;
      Object.assign(model.value, res.data);
      window.$notification?.success('保存成功');

      emit('reload');
      // show.value = false;
    });
  });
}

const rules = ref({
  name: [
    {
      required: true,
      trigger: ['blur', 'input'],
      message: '必填'
    }
  ]
});
function total(num: number) {
  model.value.staffCount = num;
}
function reload() {
  emit('reload');
}

defineExpose({
  init
});
</script>

<template>
  <ElDialog v-model="show" fullscreen title="编辑分组">
    <ElRow :gutter="25">
      <ElCol :lg="6" :md="8" :sm="24">
        <ElCard>
          <template #header>
            <h5>分组信息</h5>
          </template>
          <ElForm ref="formRef" :model="model" :rules="rules" label-position="right" label-width="80px">
            <ElFormItem label="分组名" prop="name">
              <ElInput v-model="model.name" placeholder="分组名" />
            </ElFormItem>
            <ElFormItem label="用户数" prop="staffCount">
              <ElInput v-model="model.staffCount" disabled placeholder="分组名" />
            </ElFormItem>
            <ElFormItem label="创建时间">
              <ElInput :value="model.createdTime" disabled placeholder="创建时间" />
            </ElFormItem>
            <ElFormItem label="修改时间">
              <ElInput :value="model.updateTime" disabled placeholder="修改时间" />
            </ElFormItem>
            <div style="text-align: center; padding: 10px 0 0">
              <ElButton type="primary" :disabled="enable !== true" @click="save()">保存</ElButton>
              <ElButton @click="show = false">取消</ElButton>
            </div>
          </ElForm>
        </ElCard>
      </ElCol>
      <ElCol :lg="18" :md="16" :sm="24">
        <GroupStaff :id="model.id" @total="total" @reload="reload"></GroupStaff>
      </ElCol>
    </ElRow>
  </ElDialog>
</template>
